package com.wen.rabbitmq.work.lunxun;

import com.rabbitmq.client.*;

import java.io.IOException;

public class Work1 {

    public static void main(String[] args) {
        //1.创建连接工厂
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("120.26.47.111");
        connectionFactory.setPort(5672);
        connectionFactory.setUsername("admin");
        connectionFactory.setPassword("admin");
        //虚拟访问节点
        connectionFactory.setVirtualHost("/");
        //2.创建连接connection
        Connection connection =null;
        Channel channel = null;
        try{
            connection = connectionFactory.newConnection("消费者-word1");
            //3.通过连接获取通道channel
            channel = connection.createChannel();

            Channel finalChannel = channel;
//            finalChannel.basicQos(1);
            finalChannel.basicConsume("queue1", true, new DeliverCallback() {
                @Override
                public void handle(String s, Delivery delivery) throws IOException {
                    System.out.println("work1：接收到的消息是" + new String(delivery.getBody(), "utf-8"));
                }
            }, new CancelCallback() {
                @Override
                public void handle(String s) throws IOException {
                    System.err.println("接受失败了");
                }
            });

            System.err.println("开始接受消息");
            System.in.read();

        }catch (Exception e){
            e.printStackTrace();
        }finally {
            //7.关闭通道
            if(channel!=null && channel.isOpen()){
                try {
                    channel.close();
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
            //8.关闭连接
            if(connection!=null && connection.isOpen()){
                try {
                    connection.close();
                }catch (Exception e){
                    e.printStackTrace();
                }
            }
        }
    }

}
